package com.xinyue.game.server.system;

import com.xinyue.game.server.common.GameServerConfig;
import com.xinyue.game.server.common.GameServerUtil;
import com.xinyue.network.codec.GameMessageContext;
import com.xinyue.network.message.ChannelConfirmMessageRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 连接认证处理
 * <p>
 * 当一个客户端与服务器建立连接成功之后，服务器并不能判断这个客户端是不是合法的，连接成功之后，客户端需要立刻向服务器发送一
 * 条认证消息，认证通过之后，才算建立连接成功。服务器会等待一会接收认证消息，如果在超时时间之内没有收到客户端的连接，则会主动关闭
 * 连接，以节省资源。
 * </p>
 *
 * @Author 王广帅
 * @Date 2021/1/30 22:19
 */
public class ChannelConfirmHandler extends ChannelInboundHandlerAdapter {
    private Logger logger = LoggerFactory.getLogger(ChannelConfirmHandler.class);
    private GameServerConfig gameServerConfig;
    //与客户端约定的一种token验证方式，实际应用中会加密
    private String token = "sdfsddsfdsfdf";
    //标记连接是认证成功
    private boolean isConfirmSuccess;
    private String channelId;

    public ChannelConfirmHandler(GameServerConfig gameServerConfig) {
        this.gameServerConfig = gameServerConfig;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelId = ctx.channel().id().asShortText();
        logger.debug("客户端 {} 连接成功,channelId:{}", GameServerUtil.getRemoteIP(ctx.channel()),
                channelId);
        ctx.executor().schedule(() -> {
            if (!isConfirmSuccess) {
                logger.debug("连接认证等级超时，关闭连接:{}", channelId);
                ctx.close();
            }
        }, gameServerConfig.getConfirmTimeout(), TimeUnit.SECONDS);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof GameMessageContext) {
            GameMessageContext messageContext = (GameMessageContext) msg;
            int messageId = messageContext.getHeader().getMessageId();
            if (messageId == 1) {
                ChannelConfirmMessageRequest request = (ChannelConfirmMessageRequest) messageContext.getGameMessage();
                String clientToken = request.getToken();
                if (StringUtils.isBlank(clientToken)) {
                    logger.error("token 为空，关闭连接:{}", channelId);
                    ctx.close();
                } else {
                    if (clientToken.equals(this.token)) {
                        this.isConfirmSuccess = true;
                        logger.debug("连接认证成功,{}", channelId);
                    } else {
                        logger.error("token 认证失败，关闭连接:{}", channelId);
                    }
                }
            }
        } else {
            //如果此Handler不处理这个消息，则交给下一个Handler处理
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.debug("客户端:{} 断开，channelId:{}", GameServerUtil.getRemoteIP(ctx.channel()),
                ctx.channel().id().asShortText());
    }

}
